package com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.innerService.impl;

import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.MnSapIfSOModifyServiceImpl;
import com.alibaba.cirtus.ots.application.adapter.ability.facade.serviceV2.sap.innerService.SalesOrderService;
import com.alibaba.cirtus.ots.application.adapter.ability.model.response.OrderAndDetailResponse;
import com.alibaba.cz.base.tool.log.Log;
import com.alibaba.fastjson.JSON;
import com.alibaba.lattice2.epoch.middleware.cache.runtime.service.EpochCacheService;
import com.alibaba.lattice2.epoch.sdk.model.Result;
import com.epoch.app.bcots.contants.BcOtsConstants;
import com.epoch.app.crb2btradecenter.domain.order.dto.LoadOrderListRequest;
import com.epoch.app.crb2btradecenter.domain.order.dto.QueryByOrderNosV2Request;
import com.epoch.app.crb2btradecenter.domain.order.model.Order;
import com.epoch.app.crb2btradecenter.domain.order.service.OrderService;
import com.epoch.app.crb2btradecenter.domain.orderline.dto.QuerySalesOrderLineByIdsRequest;
import com.epoch.app.crb2btradecenter.domain.orderline.model.OrderLine;
import com.epoch.app.crb2btradecenter.domain.orderline.service.OrderLineService;
import com.google.common.collect.Lists;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.context.annotation.Primary;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;

@Component
@Primary
public class SalesOrderServiceImpl implements SalesOrderService {
    private final Log log = Log.getLogger(MnSapIfSOModifyServiceImpl.class);
    @Resource
    private OrderService orderService;
    @Resource
    private OrderLineService orderLineService;
    @Resource
    private EpochCacheService epochCacheService;
    @Override
    public OrderAndDetailResponse getOrderAndDetail(String outerOrderId) {
        OrderAndDetailResponse response= new OrderAndDetailResponse();
        log.info("MnSapIfSOModifyServiceImpl getOrderAndDetail outerOrderId={}",outerOrderId);

        LoadOrderListRequest pageQueryRequest = new LoadOrderListRequest();
        pageQueryRequest.setOuterOrderId(outerOrderId);
        Result<List<Order>> loadOrderListResult = orderService.loadOrderList(pageQueryRequest);
        log.info("MnSapIfSOModifyServiceImpl getOrderAndDetail loadOrderListResult={}", JSON.toJSONString(loadOrderListResult));
        if (Objects.isNull(loadOrderListResult) || CollectionUtils.isEmpty(loadOrderListResult.getResult())){
            return null;
        }
        Order order = loadOrderListResult.getResult().get(0);
        QuerySalesOrderLineByIdsRequest querySalesOrderLineByIdsRequest = new QuerySalesOrderLineByIdsRequest();
        querySalesOrderLineByIdsRequest.setMainOrderId(String.valueOf(order.getId()));
        Result<List<OrderLine>> listResult = orderLineService.querySalesOrderLineByIds(querySalesOrderLineByIdsRequest);
        log.info("MnSapIfSOModifyServiceImpl getOrderAndDetail listResult={}",JSON.toJSONString(listResult));
        if(Objects.isNull(listResult) ||CollectionUtils.isEmpty(listResult.getResult())){
            return null;
        }
        response.setOrder(order);
        response.setOrderLineList(listResult.getResult());
        return response;
    }

    @Override
    public void unlock(String redisKey) {
        try {
            String s = epochCacheService.get(BcOtsConstants.REDIS_CACHE_CODE(), redisKey);
            log.info("SalesOrderServiceImpl unlock key={},is exist={}",redisKey,s);
            if (s == null){
                return;
            }
            boolean remove = epochCacheService.remove(BcOtsConstants.REDIS_CACHE_CODE(), Lists.newArrayList(redisKey));
            if (remove){
                log.info("SalesOrderServiceImpl ThreadId="+Thread.currentThread().getId()+"|SaleRedis key="+redisKey+"|unlock");
            }
        }catch (Exception e ){
            log.error("SalesOrderServiceImpl unlock error",e);
        }
    }

    @Override
    public OrderAndDetailResponse getOrderAndDetailByOrderBizId(String orderBizId,Integer businessType) {
        OrderAndDetailResponse response= new OrderAndDetailResponse();
        log.info("MnSapIfSOModifyServiceImpl getOrderAndDetailByOrderBizId orderBizId={}",orderBizId);

        QueryByOrderNosV2Request pageQueryRequest = new QueryByOrderNosV2Request();
        pageQueryRequest.setSalesOrderNo(Arrays.asList(orderBizId));
        pageQueryRequest.setBusinessType(businessType);
        pageQueryRequest.setStart(0);
        pageQueryRequest.setLimit(1);
        Result<List<Order>> loadOrderListResult = orderService.queryByOrderNosV2(pageQueryRequest);
        log.info("MnSapIfSOModifyServiceImpl getOrderAndDetailByOrderBizId loadOrderListResult={}", JSON.toJSONString(loadOrderListResult));
        if (Objects.isNull(loadOrderListResult) || CollectionUtils.isEmpty(loadOrderListResult.getResult())){
            return null;
        }
        Order order = loadOrderListResult.getResult().get(0);
        QuerySalesOrderLineByIdsRequest querySalesOrderLineByIdsRequest = new QuerySalesOrderLineByIdsRequest();
        querySalesOrderLineByIdsRequest.setMainOrderId(String.valueOf(order.getId()));
        Result<List<OrderLine>> listResult = orderLineService.querySalesOrderLineByIds(querySalesOrderLineByIdsRequest);
        log.info("MnSapIfSOModifyServiceImpl getOrderAndDetailByOrderBizId listResult={}",JSON.toJSONString(listResult));
        if(Objects.isNull(listResult) ||CollectionUtils.isEmpty(listResult.getResult())){
            return null;
        }
        response.setOrder(order);
        response.setOrderLineList(listResult.getResult());
        return response;
    }
}
